import random,time,requests,json

# from db import db
from model.models import db
from flask import Blueprint, request, jsonify, send_file, redirect
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r

from model.models import *
from utils.comm import get_ali_object


goods_bp = Blueprint('goods_bp',__name__)
api = Api(goods_bp)

#添加购物车
@goods_bp.route("/addcart",methods=['POST'])
def addcart():
    data = reqparse.RequestParser()
    data.add_argument("userid")
    data.add_argument("goodsid")
    args = data.parse_args()
    userid = int(args["userid"])
    goodsid = int(args["goodsid"])
    # pkey = "mycart" + str(userid)
    # r.hash_add(pkey,goodsid,userid)
    # return jsonify({"code":200,"msg":"添加购物车成功"})
    pkey = "mycart"+str(userid)
    r.hash_add(pkey,goodsid,userid)
    return jsonify({"code":200,"msg":"加入购物车成功"})


# 我的购物车
@goods_bp.route("/getcart")
def getcart():
    userid = request.args.get("userid")
    pkey = "mycart"+str(userid)
    print(pkey)
    res = r.hash_getall(pkey)
    print(">>>",res)
    cartlist = []
    for i,j in res.items():
        goodsid = i.decode()
        sql = "select id,name,price,url from course where id=%d"%int(goodsid)
        res = db.session.execute(sql)
        for i in res:
            cartlist = {"id":i["id"],"name":i["name"],"price":i["price"],"url":i["url"]}
        print(cartlist)
        return jsonify({"code": 200, "msg":"ok","cartlist": cartlist})


@goods_bp.route("/pay",methods=["POST"])
def pay():
    data=json.loads(request.data)
    userid=int(data["userid"])
    courseid=int(data["courseid"])
    sum=0
    sql = "select * from course where id=%d" % courseid
    print(sql)
    res=db.session.execute(sql)
    print("res>>",res)
    for i in res:
        cartlist = {"id": i['id'],
        "create_time": i['create_time'],
        "update_time": i['update_time'],
        "name": i['name'],
        "url": i['url'],
        "descrip": i['descrip'],
        "tcount": i['tcount'],
        "views": i['views'],
        "is_publish": i['is_publish'],
        "ctype": i['ctype'],
        "buy": i['buy'],
        "price":i["price"]}
    # print(cartlist)
    sum+=float(cartlist["price"])
    # 订单号
    number = int(str(userid) + str(random.randint(1000, 9999)))
    create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    status = 2
    try:
        usql = Vipuser_course(courseid=courseid,userid=userid)
        db.session.add(usql)
        print(usql.userid,usql.courseid,"oooooo")
        isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=courseid,number=number,tmoney=sum,status=status)
        db.session.add(isql)
        db.session.commit()
        print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
    except:
        db.session.rollback()
    # 支付
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })


@goods_bp.route("/callback")
def callback():
    try:
        sql = "update orders set status=2"
        db.session.add(sql)
        db.session.commit()
    except:
        db.session.rollback()
    # 跳转到个人中心
    return redirect('http://localhost:8080/#/zhu')